<template>
  <div style="padding: 20px;">
    <div class="el-card__body">
      <div>
        <i class="el-icon-search"></i>
        <span style="color: #303133;margin-left:10px; ">筛选搜索</span>
        <el-button class="el-button el-button--primary el-button--small" style="float: right;" @click="handSearch">
          查询搜索
        </el-button>
      </div>
      <div style="margin-top: 15px;">
        <form class="el-form el-form--inline">
          <div class="el-form-item el-form-item--small">
            <label class="el-form-item__label" style="width: 140px;color: #606266;">输入搜索：</label>
            <div class="el-form-item__content">
              <div class="input-width el-input el-input--small">
                <el-input placeholder="角色名称" v-model="inputRoleName" class="input-with-select"></el-input>
<!--                <input type="text" autocomplete="off" placeholder="角色名称" class="el-input__inner">-->
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>

    <div class="el-card__body">
      <i class="el-icon-tickets"></i>
      <span style="color: #303133;margin-left:10px; ">数据列表</span>
      <el-button type="primary" @click="handleAddUserRole" class="el-button btn-add el-button--default el-button--mini" style="margin-left: 20px;float: right;">
        添加
      </el-button>
    </div>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑用户':'添加角色'" width="520px">
      <div style="text-align:right;width: 400px; margin: auto;" >
        <div class="el-dialog__body">
          <el-form class="el-form" :modal="adminRole" >
            <el-form-item label="角色名称：">
              <el-input
                placeholder="请输入角色名称"
                v-model="adminRole.roleName"
                autocomplete="off">
              </el-input>
            </el-form-item>
            <el-form-item label="角色名称：">
              <el-input
                type="textarea"
                v-model="adminRole.remark"
                autocomplete="off"
                :rows="2"
                placeholder="请输入内容"
                >
              </el-input>
            </el-form-item>
          </el-form>
        </div>

        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="addOrUpdateRole()">确定</el-button>
      </div>
    </el-dialog>


    <el-dialog :visible.sync="dialogVisibleRole" :title="dialogTypeRole==='role'?'分配角色':''" width="458px">
      <div style="text-align:right;width: 400px;" >
        <form class="el-form">
          <div class="el-form-item el-form-item--small">
            <div class="el-form-item__content" style="margin-left: 10px;">
              <div class="el-input el-input--small">
                <el-select v-model="value1" multiple placeholder="请选择" style="width:100%">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </div>
            </div>
          </div>
        </form>

        <el-button type="danger" @click="dialogVisibleRole=false">取消</el-button>
        <el-button type="primary" @click="confirmRole">确定</el-button>
      </div>
    </el-dialog>

    <div style="position:relative;">
      <el-table :data="rolesList" style="width: 100%;margin-top:30px;" border >
        <div slot="empty" class="tableEmpty">
<!--          <img src="../../../public/nodata.png"  width-="100%" height="266px">-->
          暂无数据
        </div>
        <el-table-column
          label="编号"
          type="index"
          width="100"
          :index="indexMethod"
          align='center'>
        </el-table-column>
        <el-table-column align="center" label="角色名称" width="200">
          <template slot-scope="scope">
            {{ scope.row.roleName }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="描述" width="250">
          <template slot-scope="scope">
            {{ scope.row.remark }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作人">
          <template slot-scope="scope">
            {{ scope.row.gmtModifyUser }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="创建日期" width="220">
          <template slot-scope="scope">
            {{ scope.row.gmtCreateTime }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="修改日期" width="220">
          <template slot-scope="scope">
            {{ scope.row.gmtModifyTime }}
          </template>
        </el-table-column>
      <!--  <el-table-column align='center' label="是否启用">
          <template slot-scope="scope">
            <el-switch
              :active-value="1"
              :inactive-value="0"
              v-model="scope.row.status">
            </el-switch>
          </template>
          </el-switch>
        </el-table-column>-->
        <el-table-column fixed="right" label="操作" width="200" align='center'>
          <template slot-scope="scope">
            <el-button @click="allocationRole(scope.row)" type="text" size="small">分配菜单</el-button>
            <el-button @click="allocationRole(scope.row)" type="text" size="small">分配资源</el-button>
            <el-button type="text" @click="handleEdit(scope)" size="small">编辑</el-button>
            <el-button type="text" @click="handDelRole(scope)" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="block">
        <div style="float: right;">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="2">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import path from 'path'
  import { Message } from 'element-ui'
  import { deepClone } from '@/utils'
  import { getAllUserInfo, delUser} from '@/api/user'
  import { getRoutes, getRoles, addRole, deleteRole, updateRole,findRoleList ,findByRoleId} from '@/api/role'
  const defaultRole = {
    key: '',
    name: '',
    description: '',
    routes: [],
  }

  export default {
    setup() {
      const checked = ref<boolean>(false);
      return {
        checked,
      };
      const value = ref<number>(1);
      return {
        value,
      };
    },
    data() {
      return {
        role: Object.assign({}, defaultRole),
        routes: [],
        rolesList: [],
        userInfoList: [],
        value1: true,
        dialogVisible: false,
        dialogVisibleRole: false,
        currentPage: 1,
        inputRoleName:'',
        radio: 'true',
        dialogType: 'new',
        dialogTypeRole: 'role',
        checkStrictly: false,
        adminRole:{
          id: "",
          roleName: null,
          remark: null,
        },
        defaultProps: {
          children: 'children',
          label: 'title'
        },
        options: [{
          value: '0',
          label: '商品管理员'
        }, {
          value: '1',
          label: '订单管理员'
        }, {
          value: '2',
          label: '超级管理员'
        }],
        value1: [],
      }
    },
    computed: {
      routesData() {
        return this.routes
      }
    },
    created() {
      // Mock: get all routes and roles list from server
      this.getRoutes()
      this.getRoles()
      this.getAllUserInfo()
    },
    methods: {
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
      },
      indexMethod(index) {
        return index +1;
      },
      async getRoutes() {
        const res = await getRoutes()
        this.serviceRoutes = res.data
        this.routes = this.generateRoutes(res.data)
      },
      //获取角色列表
      async getRoles() {
        const res = await getRoles()
        this.rolesList = res.data
      },
      async getAllUserInfo() {
        const res = await getAllUserInfo()
        this.userInfoList = res.data
      },
      // Reshape the routes structure so that it looks the same as the sidebar
      generateRoutes(routes, basePath = '/') {
        const res = []

        for (let route of routes) {
          // skip some route
          if (route.hidden) { continue }

          const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)

          if (route.children && onlyOneShowingChild && !route.alwaysShow) {
            route = onlyOneShowingChild
          }

          const data = {
            path: path.resolve(basePath, route.path),
            title: route.meta && route.meta.title

          }

          // recursive child routes
          if (route.children) {
            data.children = this.generateRoutes(route.children, data.path)
          }
          res.push(data)
        }
        return res
      },
      generateArr(routes) {
        let data = []
        routes.forEach(route => {
          data.push(route)
          if (route.children) {
            const temp = this.generateArr(route.children)
            if (temp.length > 0) {
              data = [...data, ...temp]
            }
          }
        })
        return data
      },
      handDelRole({row}) {
        this.$confirm('确定要删除吗?', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async() => {
            await deleteRole(row.id)
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            this.getRoles();
          })
          .catch(err => { console.error(err) })
      },
      handleAddUserRole() {
        this.role = Object.assign({}, defaultRole)
        if (this.$refs.tree) {
          this.$refs.tree.setCheckedNodes([])
        }
        this.dialogType = 'new'
        this.dialogVisible = true
      },
      //搜索
      async handSearch() {
        if (this.inputRoleName == '' || this.inputRoleName == undefined){
          this.inputRoleName = null;
        }
        this.adminRole.roleName = this.inputRoleName;
        const res = await findRoleList(this.adminRole);
        if (res.data == "" || res.data == null) {
          this.rolesList = [];
        } else {
          this.rolesList = res.data
        }
      },
      async handleEdit(scope) {
        this.dialogType = 'edit'
        this.dialogVisible = true
        this.checkStrictly = true
        this.role = deepClone(scope.row)
        const res = await findByRoleId(scope.row.id);
        console.log(res.data);
        this.adminRole.id = res.data.id;
        this.adminRole.roleName = res.data.roleName;
        this.adminRole.remark = res.data.remark;
        this.$nextTick(() => {
          const routes = this.generateRoutes(this.role.routes)
          this.$refs.tree.setCheckedNodes(this.generateArr(routes))
          // set checked state of a node not affects its father and child nodes
          this.checkStrictly = false
        })
      },
      //分配角色
      allocationRole() {
        this.role = Object.assign({}, defaultRole)
        if (this.$refs.tree) {
          this.$refs.tree.setCheckedNodes([])
        }
        this.dialogType = 'role'
        this.dialogVisibleRole = true
      },
      handleDelete({ $index, row }) {
        this.$confirm('Confirm to remove the role?', 'Warning', {
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Cancel',
          type: 'warning'
        })
          .then(async() => {
            await deleteRole(row.key)
            this.rolesList.splice($index, 1)
            this.$message({
              type: 'success',
              message: 'Delete succed!'
            })
          })
          .catch(err => { console.error(err) })
      },
      generateTree(routes, basePath = '/', checkedKeys) {
        const res = []

        for (const route of routes) {
          const routePath = path.resolve(basePath, route.path)

          // recursive child routes
          if (route.children) {
            route.children = this.generateTree(route.children, routePath, checkedKeys)
          }

          if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
            res.push(route)
          }
        }
        return res
      },
      async addOrUpdateRole() {
        const isEdit = this.dialogType === 'add'

        console.log(this.adminRole);
        await addRole(this.adminRole)
          .then(async(response) => {
            if (response.code === 20000){
              Message({
                message: response.message,
                type: 'success',
                duration: 2*10000
              })
              this.dialogVisible = false;
              this.getRoles();
            }else {
              Message({
                message: response.message,
                type: 'failure',
                duration: 5 * 10000
              })
            }
          })

        const checkedKeys = this.$refs.tree.getCheckedKeys()
        this.role.routes = this.generateTree(deepClone(this.serviceRoutes), '/', checkedKeys)

        if (isEdit) {
          await updateRole(this.role.key, this.role)
          for (let index = 0; index < this.rolesList.length; index++) {
            if (this.rolesList[index].key === this.role.key) {
              this.rolesList.splice(index, 1, Object.assign({}, this.role))
              break
            }
          }
        } else {
          const { data } = await addRole(this.role)
          this.role.key = data.key
          this.rolesList.push(this.role)
        }
        //
        // const { description, key, name } = this.role
        // this.dialogVisible = false
        // this.$notify({
        //   title: 'Success',
        //   dangerouslyUseHTMLString: true,
        //   message: `
        //     <div>Role Key: ${key}</div>
        //     <div>Role Name: ${name}</div>
        //     <div>Description: ${description}</div>
        //   `,
        //   type: 'success'
        // })
      },
      // reference: src/view/layout/components/Sidebar/SidebarItem.vue
      onlyOneShowingChild(children = [], parent) {
        let onlyOneChild = null
        const showingChildren = children.filter(item => !item.hidden)

        // When there is only one child route, the child route is displayed by default
        if (showingChildren.length === 1) {
          onlyOneChild = showingChildren[0]
          onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
          return onlyOneChild
        }

        // Show parent if there are no child route to display
        if (showingChildren.length === 0) {
          onlyOneChild = { ... parent, path: '', noShowingChildren: true }
          return onlyOneChild
        }

        return false
      }
    }
  }
</script>

<style scoped>
  .el-card__body{
    border: 1px #EBEEF5 solid;
  }
  .block{
    position: absolute;
    width: 100%;
    border: 1px #EBEEF5 solid;
    bottom: -50px;
  }
  .tableEmpty {
    display: block;
    width: 100%;
    background-size: 100% 100%;
  }
</style>
